/**
 * 
 */
package hu.cubussapiens.client.core.query;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.httpclient.methods.RequestEntity;
import org.w3c.dom.Document;

/**
 * @author balage
 *
 */
public class XMLRequestEntity implements RequestEntity {

	final Document doc;
	
	final byte[] buffer;
	
	public XMLRequestEntity(Document doc) throws TransformerFactoryConfigurationError, TransformerException, IOException {
		this.doc = doc;
		Transformer t = TransformerFactory.newInstance().newTransformer();
		t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
		t.setOutputProperty(OutputKeys.INDENT,"yes");
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		t.transform(new DOMSource(doc),new StreamResult(buffer));
		buffer.flush();
		this.buffer = buffer.toByteArray();
	}
	
	/* (non-Javadoc)
	 * @see org.apache.commons.httpclient.methods.RequestEntity#getContentLength()
	 */
	@Override
	public long getContentLength() {
		return buffer.length;
	}

	/* (non-Javadoc)
	 * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
	 */
	@Override
	public String getContentType() {
		return "text/xml";
	}

	/* (non-Javadoc)
	 * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
	 */
	@Override
	public boolean isRepeatable() {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream)
	 */
	@Override
	public void writeRequest(OutputStream out) throws IOException {
		out.write(this.buffer);
	}

}
